package com.zx.account.controller;

import cn.hutool.core.date.DateUtil;
import com.zx.account.entity.ATypeDetail;
import com.zx.account.entity.Account;
import com.zx.account.entity.User;
import com.zx.account.model.ATypeDetailDto;
import com.zx.account.model.ResponseDto;
import com.zx.account.service.ATypeService;
import com.zx.account.service.AccountService;
import com.zx.util.Constants;
import com.zx.util.SessionDataUtil;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * @version v1.0
 * @Project: managing-self
 * @Title: AccountController
 * @Description: 消费记录
 * @author: zhangxue
 * @date: 2019年10月4日下午10:15:35
 * @company: 未知
 * @Copyright: Copyright (c) 2015
 */
@Slf4j
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private ATypeService aTypeService;

    /**
     * 计算集合里面的消费总额
     *
     * @param li
     * @return
     */
    public static BigDecimal getSum(List<Account> li) {
        Optional<BigDecimal> reduce = li.stream()
                .map(Account::getPrice)
                .reduce(BigDecimal::add);
        return reduce.orElse(BigDecimal.ZERO);
    }

    /**
     * 计算一共是多少天
     *
     * @param list
     * @return
     */
    public static long getDays(List<Account> li) {
        long count = li.stream()
                .map(x -> x.getConsumeDate().getTime())
                .distinct()//去重
                .count();// 统计数量
        return count;
    }

    /**
     * 消费记录添加页面
     *
     * @param
     * @return
     */
    @RequestMapping("/addView")
    public ModelAndView initAccount(ModelAndView m) {
        User user = SessionDataUtil.getUserInfo();
        log.info("访问消费记录添加页面 user={}", user);
        m.addObject("types", this.aTypeService.getByUserId(user.getId()));
        m.addObject("today", DateUtil.format(new Date(), Constants.DATE_FORMAT_4));
        m.setViewName("account/addView");
        return m;
    }

    /**
     * @param account 页面传入的字段，主要是consumeDate, tId, price, description
     * @return
     * @Title: 新增一条消费记录
     * @date: 2019年10月5日下午3:22:31
     * @author: zhangxue
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseDto<String> add(Account account) {
        User user = SessionDataUtil.getUserInfo();
        log.info("新增一条消费记录 account={} user={}", account, user);
        try {
            // 初始化字段
            account.setUserId(user.getId()).setCreateTime(new Date());
            return accountService.insert(account) ? ResponseDto.ok("") : ResponseDto.no("");
        } catch (Exception e) {
            log.error("新增一条消费记录出现异常", e);
        }
        return ResponseDto.no("新增一条消费记录出现异常", "");
    }

    @PostMapping("/addDetail")
    @ResponseBody
    public ResponseDto<String> addDetail(ATypeDetail detail) {
        User user = SessionDataUtil.getUserInfo();
        log.info("新增一条详情 detail={} user={}", detail, user);
        try {
            // 初始化字段
            detail.setUserId(user.getId()).setCreateTime(new Date()).setUpdateTime(new Date()).setDescription("");
            return aTypeService.insert(detail) ? ResponseDto.ok("") : ResponseDto.no("");
        } catch (Exception e) {
            log.error("新增一条消费记录出现异常", e);
        }
        return ResponseDto.no("新增一条消费记录出现异常", "");
    }

    @PostMapping("/getDetail")
    @ResponseBody
    public ResponseDto<List<ATypeDetailDto>> getDetail(Integer tId, Integer tDId) {
        User user = SessionDataUtil.getUserInfo();
        log.info("查询消费类型详情 user={}, tId={}, tDId={}", user, tId, tDId);
        try {
            // 初始化字段
            List<ATypeDetailDto> details = this.aTypeService.getDetailByUserId(user.getId());
            List<ATypeDetailDto> resList = details.stream().filter(d -> {
                if (tId != null && !Objects.equals(tId, d.getTId())) {
                    return false;
                }
                if (tDId != null && !Objects.equals(tDId, d.getId())) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());

            return ResponseDto.ok(resList);
        } catch (Exception e) {
            log.error("查询消费类型详情出现异常", e);
        }
        return ResponseDto.no("查询消费类型详情出现异常");
    }
}
